﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sofire.DataComm.Net.Async;
using Sofire.DataComm;
using Sofire.DataComm.Net;

namespace DataCommTest.AsyncTest
{
    public class AsyncServerTestDemo : ITest
    {
        AsyncSocketServer Server;
        public AsyncServerTestDemo()
        {
            this.Server = new AsyncSocketServer("server", new SocketInfo(ProtocolMode.Tcp, 9595));
            this.Server.SocketConnected += new AsyncSocketServerEventHandler(Server_SocketConnected);
            this.Server.SocketDisconnected += new AsyncSocketServerEventHandler(Server_SocketDisconnected);
            this.Server.SocketFaild += new AsyncSocketExceptionEventHandler(Server_SocketFaild);
            this.Server.StateChanged += new CommunicationStateEventHandler(Server_StateChanged);
            this.Server.AsyncReceive += new AsyncSocketReceiveEventHandler(Server_AsyncReceive);
        }

        void Server_AsyncReceive(object sender, AsyncSocketReceiveEventArgs e)
        {
            if(e.Mode == ReceiveMode.Full)
            {
                var s = e.GetString();
                if(s == "请求已经收到！")
                {
                    Console.WriteLine("客户端已经收到请求了");
                }
                else
                {
                    e.Remote.Send("我们收到来自客户端的" + s);
                }
            }
        }

        void Server_StateChanged(object sender, CommunicationStateEventArgs e)
        {
            if(e.State == CommunicationState.Failed)
                Console.WriteLine("服务器异常 {0} ...", (e as CommunicationFailedStateEventArgs).Exception);
            else
                Console.WriteLine("服务器状态 {0} ...", e.State);
        }

        void Server_SocketConnected(object sender, AsyncSocketServerEventArgs e)
        {
            //Console.WriteLine("客户 {0} 已连接成功...", e.Socket.RemoteEndPoint);
        }

        void Server_SocketDisconnected(object sender, AsyncSocketServerEventArgs e)
        {
            //Console.WriteLine("客户 {0} 已断开连接...", e.Socket.RemoteEndPoint);
        }

        void Server_SocketFaild(object sender, AsyncSocketExceptionEventArgs e)
        {
            Console.WriteLine("客户端 {0} 发生了错误（{1}）...", e.Socket.RemoteEndPoint, e.Exception);
        }

        public void Test()
        {
            this.Server.Open();
        }

        ~AsyncServerTestDemo()
        {
            this.Server.Close();
        }
    }
}
